/*
 * Copyright (c) 2018. Beyondsoft Corporation.
 * All Rights Reserved.
 *
 * BEYONDSOFT CONFIDENTIALITY
 *
 * The information in this file is confidential and privileged from Beyondsoft Corporation,
 * which is intended only for use solely by Beyondsoft Corporation.
 * Disclosure, copying, distribution, or use of the contents of this file by persons other than Beyondsoft Corporation
 * is strictly prohibited and may violate applicable laws.
 */

package com.base.common.basemodule;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.WindowManager;

import com.base.common.R;

/**
 * @author xzk
 * @data 2019/6/25
 * @email xiezhengkun@beyondsoft.com
 * @remark dialog工具类
 */
public class LoadingDialog extends Dialog {

    /**
     * 本处理方式是为了延长关闭时间，避免闪屏出现
     */
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                try {
                    LoadingDialog.this.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public LoadingDialog(Context context) {
        super(context);
        /**
         * 设置对话框背景透明
         */
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.loading_layout);
        setCanceledOnTouchOutside(false);
    }

    public void showDialog() {
        // 设置居中
        this.getWindow().getAttributes().gravity = Gravity.CENTER;
        WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
        // 设置背景层透明度
        layoutParams.dimAmount = 0.2f;
        this.getWindow().setAttributes(layoutParams);
        // 显示
        try {
            this.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭
     */
    public void dismissDialog() {
        try {
            handler.sendEmptyMessageDelayed(1,600);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除变量
     */
    public void recycleSource(){
        if(handler != null){
            handler.removeMessages(1);
            try {
                LoadingDialog.this.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
